package cn.laike.common.utils.mp;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import cn.laike.common.utils.HttpRequest;
import cn.laike.common.utils.XMLUtils;
import cn.laike.common.utils.mp.aes.AesException;
import cn.laike.common.utils.mp.aes.WXBizMsgCrypt;
import net.sf.json.JSONObject;

public class MpUtils {

	/** 来客平台*/
	public final static String appId = "wx03d1ee4e9d571c3f";
	public final static String appSecret = "dc96710b57e5da5c1080f1f94082f50f";
	
	
	public final static String encodingAesKey = "49Kl4SIXDlblPBfv0JLn02aTwxIw8OR4DJEBv6r4LbW";
	public final static String token = "laikeglotejvlldjhfgzx";
	
	
	/*****************************************授权流程  start*******************************************/
	/**
	 * 1、推送component_verify_ticket协议
	 * @return
	 * @throws AesException 
	 */
	public static Map<String, String> wxBizMsgCrypt(String encrypt){
		try {
			if(StringUtils.isNotEmpty(encrypt)){
				WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
				String result = pc.decrypt(encrypt);
				System.out.println("解密后明文: " + result);
				Map<String, String> xmlMap = XMLUtils.xml2Map(result);
				return xmlMap;
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	/**
	 * 2、获取第三方平台component_access_token
	 * @return
	 */
	public static String api_component_token(String componentVerifyTicket){
		if(StringUtils.isNotEmpty(componentVerifyTicket)){
			JSONObject param = new JSONObject();
			param.put("component_appid", appId);
			param.put("component_appsecret", appSecret);
			param.put("component_verify_ticket", componentVerifyTicket);
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/component/api_component_token", param);
			System.out.println(result);
			JSONObject json = JSONObject.fromObject(result);
			System.out.println(result);
			return json.getString("component_access_token");
		}else{
			return null;
		}
		
	}
	
	/**
	 * 3、获取预授权码pre_auth_code
	 * @return
	 */
	public static String api_create_preauthcode(String componentAccessToken){
		if(StringUtils.isNotEmpty(componentAccessToken)){
			JSONObject param = new JSONObject();
			param.put("component_appid", appId);
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token="+componentAccessToken, param);
			JSONObject json = JSONObject.fromObject(result);
			System.out.println(result);
			return json.getString("pre_auth_code");
		}else{
			return null;
		}
	}
	
	/**
	 * 4、使用授权码换取公众号或小程序的接口调用凭据和授权信息
	 * @return
	 */
	public static JSONObject api_query_auth(String componentAccessToken,String authorizationCode){
		if(StringUtils.isNotEmpty(componentAccessToken)){
			JSONObject param = new JSONObject();
			param.put("component_appid", appId);
			param.put("authorization_code", authorizationCode);
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token="+componentAccessToken, param);
			System.out.println("4、使用授权码换取公众号或小程序的接口调用凭据和授权信息");
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 5、获取（刷新）授权公众号或小程序的接口调用凭据（令牌）
	 * @return
	 */
	public static JSONObject api_authorizer_token(String componentAccessToken,String authorizerAppid,String authorizerRefreshToken){
		if(StringUtils.isNotEmpty(componentAccessToken)){
			JSONObject param = new JSONObject();
			param.put("component_appid", appId);
			param.put("authorizer_appid", authorizerAppid);
			param.put("authorizer_refresh_token", authorizerRefreshToken);
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token="+componentAccessToken, param);
			System.out.println("获取（刷新）授权公众号或小程序的接口调用凭据（令牌）");
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 6、获取授权方的帐号基本信息
	 * @return
	 */
	public static JSONObject api_get_authorizer_info(String componentAccessToken,String authorizerAppid){
		if(StringUtils.isNotEmpty(componentAccessToken)){
			JSONObject param = new JSONObject();
			param.put("component_appid", appId);
			param.put("authorizer_appid", authorizerAppid);
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token="+componentAccessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	
	/**
	 * 7、获取授权方的选项设置信息
	 * @return
	 */
	public static JSONObject api_get_authorizer_option(String componentAccessToken,String authorizerAppid,String optionName){
		if(StringUtils.isNotEmpty(componentAccessToken)){
			JSONObject param = new JSONObject();
			param.put("component_appid", appId);
			param.put("authorizer_appid", authorizerAppid);
			param.put("option_name", optionName);
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token="+componentAccessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 8、设置授权方的选项信息
	 * @return
	 */
	public static JSONObject api_set_authorizer_option(String componentAccessToken,String authorizerAppid,String optionName,String optionValue){
		if(StringUtils.isNotEmpty(componentAccessToken)){
			JSONObject param = new JSONObject();
			param.put("component_appid", appId);
			param.put("authorizer_appid", authorizerAppid);
			param.put("option_name", optionName);
			param.put("option_value", optionValue);
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/component/api_set_authorizer_option?component_access_token="+componentAccessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	/*****************************************授权流程  end*******************************************/
	
	
	/*****************************************代码管理  start*******************************************/
	
	/**
	 * 1、为授权的小程序帐号上传小程序代码
	 * @param accessToken 请使用第三方平台获取到的该小程序授权的authorizer_access_token
	 * @param templateId 代码库中的代码模版ID
	 * @param extJson 第三方自定义的配置
	 * @param userVersion  代码版本号，开发者可自定义（长度不要超过64个字符）
	 * @param userDesc  代码描述，开发者可自定义
	 * @return
	 */
	public static JSONObject commit(String accessToken,String templateId,String extJson,String userVersion,String userDesc){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			param.put("template_id", templateId);
			param.put("ext_json", extJson);
			param.put("user_version", userVersion);
			param.put("user_desc", userDesc);
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/commit?access_token="+accessToken, param);
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 2、获取体验小程序的体验二维码
	 * @param accessToken 请使用第三方平台获取到的该小程序授权的authorizer_access_token
	 * @param templateId 代码库中的代码模版ID
	 * @param extJson 第三方自定义的配置
	 * @param userVersion  代码版本号，开发者可自定义（长度不要超过64个字符）
	 * @param userDesc  代码描述，开发者可自定义
	 * @return
	 */
	public static void get_qrcode(String accessToken,String path,String filepath,String filename){
		if(StringUtils.isNotEmpty(accessToken)){
			String url = "https://api.weixin.qq.com/wxa/get_qrcode";
			String param = "access_token=" + accessToken;
			if(StringUtils.isNotEmpty(path)) {
				param += "&path="+path;
			}
			
			String result = HttpRequest.sendGetFile(url, param,filepath ,filename );
			System.out.println(result);
		}
	}
	
	/**
	 * 3、获取授权小程序帐号已设置的类目
	 * @param accessToken
	 * @return
	 */
	public static JSONObject get_category(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			String result = HttpRequest.sendGet("https://api.weixin.qq.com/wxa/get_category", "access_token=" + accessToken);
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 4、获取小程序的第三方提交代码的页面配置（仅供第三方开发者代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject get_page(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			String result = HttpRequest.sendGet("https://api.weixin.qq.com/wxa/get_page", "access_token=" + accessToken);
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 5、将第三方提交的代码包提交审核（仅供第三方开发者代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject submit_audit(String accessToken,JSONObject param){
		if(StringUtils.isNotEmpty(accessToken)){
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/submit_audit?access_token=" + accessToken, param);
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 7、查询某个指定版本的审核状态（仅供第三方代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject get_auditstatus(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/get_auditstatus?access_token=" + accessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 8、查询最新一次提交的审核状态（仅供第三方代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject get_latest_auditstatus(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			String result = HttpRequest.sendGet("https://api.weixin.qq.com/wxa/get_latest_auditstatus", "access_token=" + accessToken);
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 9、发布已通过审核的小程序（仅供第三方代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject release(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/release?access_token=" + accessToken, param);
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 10、修改小程序线上代码的可见状态（仅供第三方代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject change_visitstatus(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/change_visitstatus?access_token=" + accessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 11. 小程序版本回退（仅供第三方代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject revertcoderelease(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/revertcoderelease?access_token=" + accessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 12. 查询当前设置的最低基础库版本及各版本用户占比（仅供第三方代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject getweappsupportversion(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/wxopen/getweappsupportversion?access_token=" + accessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 13. 设置最低基础库版本（仅供第三方代小程序调用）
	 * @param accessToken
	 * @return
	 */
	public static JSONObject setweappsupportversion(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/wxopen/setweappsupportversion?access_token=" + accessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	
	/**
	 * 
	 * 14. 设置小程序“扫普通链接二维码打开小程序”能力
	 * 此功能包括4个接口：
	(1)增加或修改二维码规则
	(2)获取已设置的二维码规则
	(3)获取校验文件名称和内容
	(4)删除已设置的二维码规则
	(5)发布已设置的二维码规则
	 * @param accessToken
	 * @return
	 */

	/**
	 * 15. 小程序审核撤回
	 * @param accessToken
	 * @return
	 */
	public static JSONObject undocodeaudit(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/undocodeaudit?access_token=" + accessToken, param);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	public static JSONObject modify_domain(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			param.put("action", "set");
			String[] requestdomain = {"https://apis.map.qq.com","https://laikehttps.hbweiyinqing.cn"};
			param.put("requestdomain", requestdomain);
			String[] wsrequestdomain = {"https://laikehttps.hbweiyinqing.cn"};
			param.put("wsrequestdomain", wsrequestdomain);
			param.put("uploaddomain", requestdomain);
			param.put("downloaddomain", requestdomain);
			
		
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/modify_domain?access_token=" + accessToken, param);
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	public static JSONObject setwebviewdomain(String accessToken){
		if(StringUtils.isNotEmpty(accessToken)){
			JSONObject param = new JSONObject();
			String[] requestdomain = {"https://laikehttps.hbweiyinqing.cn"};
			param.put("webviewdomain", requestdomain);
			System.out.println(param.toString());
			String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=" + accessToken, param);
			System.out.println(result);
			return JSONObject.fromObject(result);
		}else{
			return null;
		}
	}
	/*****************************************代码管理  end*********************************************/

	
	
	public static void main(String[] args) throws Exception {
	
		String accessToken = "";
		accessToken = "19_GvVGzjiYlRoO3kx-4Va0edQ3hS3fg3EM72t9dXh6VIazAHw_t2PAhJQsPNu4c8fl8837Ek-0p4kw4LmEFKLZohZDvkirrYTxAiwRfuY6QcdU0mH04VcazsnEGm-Sj5wIa1ET4OTr4p3cluQyPSEgAFDDGS";
		//setwebviewdomain(accessToken);
		
		modify_domain(accessToken);
//		String accessToken = "18_YFOt60dX86lDVZ-Zij1t-mStrHYLk0QfXVDxznRjjgi8q0PnoPD19tOXR7OOIeV3NT-0i74LJ6FUY_DjJ7zWNzRo1e5Ll2-EoL6WOsQhn1tDECByPJFEZG2D2crIzSML9TOV_DdaF7StIj1QDOPfAGDLWX-epIHg2xulvQhmCeSl2cu_-xRnv2ZymlmK2X7A8Im9bh3M7MboMPlhfgnbuU7le8pgHq33EOHGeAGDWPO";
//		System.out.println(get_latest_auditstatus(accessToken));
		/*if(true){
			String encrypt = "7bZNXF1f3bKsN72jHCn2LSsoaTdqlyHp5nwgeJeyk2WSK8J7VYazJhu18y0yU1zQPg2c4zE3SC2ruFzmcndoIyZf3BuEYzYcjsGT0cVpjCKENVG1xsxVNJ6a5KwBQnfRxVbJ+5vJK9qfrV9q6knzuY0ZybG0yFq2R92LM5A5hxSWunST8CxwSlVkTtDY78rSLcv13b5IJJTTuTQIRcjO/PpDUje51pxznH86jkdOJ0Vrr3Dk0oMrrx7ROEjabbukiRvRiC+LfT16KUu8D8CBZHzE5vIixDHyrBXzp5RJ7emkGXTo+eP2OZtB8ADJ4IJRgRJ+JaQiH7fF9yOYHLO7XAmyDpxMMIvwQaljhgeWdVg94IEBjI52z+A/fim1rU4RlKBcc57lK/V7sqkFKbusg1smrp9M3X+OmCsZaUVMN0uDTIUVwxTB86QNQEx47Jj/4J6bjPsRjJGWtUI/eiPXaw==";
			String component_verify_ticket = component_verify_ticket(encrypt);
			System.out.println("解密后明文: " + component_verify_ticket);
			
			String component_access_token = api_component_token(component_verify_ticket);
			System.out.println("component_access_token" + component_access_token);
			
			String pre_auth_code = api_create_preauthcode(component_access_token);
			System.out.println("授权码:"+pre_auth_code);
		}else{
			String pro_auth_code = "preauthcode@@@RuvI5_pd2EwNHDad0HDgiLzfXFVi0X4ufsZUejyGP6H7T8tIUlp5Rffq2SKS9Wzf";
			@SuppressWarnings("deprecation")
			String web = URLEncoder.encode("http://182s163a59.imwork.net/admin/api/mp/login");
			String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid="+appId+"&pre_auth_code="+pro_auth_code+"&biz_appid=gh_e1770ea6df3e&redirect_uri="+web;
			System.out.println(url);
		}*/
		
		//pc.verifyUrl(null, null, null, null);
		
		//api_component_token("ticket@@@LXd36Dn2-fw5rOVnPkOn1ZoBLa69nWDKXNkp6Pv7Ggwh-eZfa6CAHnrHlhgWVTMosEF-0zzt8KacrAvMbp4X4w");
		
		//api_create_preauthcode("17_O_Wy3-ufMfGS0fmJViF7WmXdCz_c6Zi_s_SU2J6OihsrfA_goYuw2Bcchmx0Q75M8wZyCxoM1c1Ptqap8wS7OTyYds-9Um47kZPNI82oIAlkwXIfUmXdeY9krCX2DYZ3AcjESpDHV1kb3RqvWJZaAGAJWM");
	
		//{"pre_auth_code":"preauthcode@@@Of9blmZ3a8y7kKSb2Sch6luzDNK7ISborQFta9IabOhyDxQpbsGPkJ-85Z4VU0VU","expires_in":1800}
		//System.out.println(URLEncoder.encode("http://182s163a59.imwork.net/admin/api/mp/chat"));
		//String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=wx70db286ac68964ea&pre_auth_code=preauthcode@@@Of9blmZ3a8y7kKSb2Sch6luzDNK7ISborQFta9IabOhyDxQpbsGPkJ-85Z4VU0VU&redirect_uri=http%3A%2F%2F182s163a59.imwork.net%2Fadmin%2Fapi%2Fmp%2Fchat&auth_type=1&biz_appid=gh_e1770ea6df3e";
	}
}
